package com.aiyige.page.selectinterest;


import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.aiyige.BuildConfig;
import com.aiyige.R;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.base.eventbus.EventInterestSelectedAllCleared;
import com.aiyige.base.eventbus.EventInterestSelectedStateChanged;
import com.aiyige.model.tag.Tag;
import com.aiyige.page.selectinterest.adapter.InterestAdapter;
import com.aiyige.page.selectinterest.model.IndustryItem;
import com.aiyige.page.selectinterest.model.InterestItem;
import com.aiyige.setup.model.Setup;
import com.aiyige.setup.util.SetupUtil;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.AppUtils;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.dialog.LoadingDialog;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.ResponseBody;
import retrofit2.Response;


public class InterestPage extends Fragment {
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    Unbinder unbinder;
    IndustryItem data;
    List<IndustryItem> allData;
    InterestAdapter interestAdapter;

    public InterestPage() {

    }

    public List<IndustryItem> getAllData() {
        return allData;
    }

    public void setAllData(List<IndustryItem> allData) {
        this.allData = allData;
    }

    public IndustryItem getData() {
        return data;
    }

    public void setData(IndustryItem data) {
        this.data = data;
    }

    public static InterestPage newInstance(IndustryItem industryItem, List<IndustryItem> industryItemList) {
        InterestPage fragment = new InterestPage();
        fragment.setData(industryItem);
        fragment.setAllData(industryItemList);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.page_interest, container, false);
        unbinder = ButterKnife.bind(this, view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setItemAnimator(null);
        interestAdapter = new InterestAdapter();
        interestAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                int totalSelectCount = 0;
                for (IndustryItem interestItem : allData) {
                    totalSelectCount += interestItem.getSelectedInterestItemList().size();
                }
                List<InterestItem> selectedList = data.getSelectedInterestItemList();
                int currentIndustrySelectCount = selectedList.size();
                InterestItem interestItem = interestAdapter.getItem(position);
                boolean allSelectedChecked = false;
                for (InterestItem i : selectedList) {
                    if (i.isAllSelected()) {
                        allSelectedChecked = i.isSelected();
                        break;
                    }
                }

                if (interestItem.isAllSelected()) {
                    if (!interestItem.isSelected() && totalSelectCount >= SelectInterestPage.MAX_SELECT_NUM && currentIndustrySelectCount == 0) {
                        ToastX.show(String.format(view.getContext().getString(R.string.reach_max_interest_select_num), SelectInterestPage.MAX_SELECT_NUM));
                        return;
                    } else {
                        for (int i = 0; i < interestAdapter.getItemCount(); ++i) {
                            if (i != position) {
                                interestAdapter.getItem(i).setSelected(false);
                            }
                        }
                        interestItem.setSelected(!interestItem.isSelected());
                        interestAdapter.notifyDataSetChanged();
                    }
                } else {
                    if (!interestItem.isSelected() && !allSelectedChecked && totalSelectCount >= SelectInterestPage.MAX_SELECT_NUM) {
                        ToastX.show(String.format(view.getContext().getString(R.string.reach_max_interest_select_num), SelectInterestPage.MAX_SELECT_NUM));
                        return;
                    } else {
                        for (int i = 0; i < interestAdapter.getItemCount(); ++i) {
                            if (interestAdapter.getItem(i).isAllSelected()) {
                                InterestItem allSelectedIntem = interestAdapter.getItem(i);
                                allSelectedIntem.setSelected(false);
                                interestAdapter.setData(i, allSelectedIntem);
                            }
                        }
                        interestItem.setSelected(!interestItem.isSelected());
                        interestAdapter.setData(position, interestItem);
                    }
                }
                EventBus.getDefault().post(new EventInterestSelectedStateChanged(data.getId()));
            }
        });
        recyclerView.setAdapter(interestAdapter);
        doRefresh();
        EventBus.getDefault().register(this);
        return view;
    }

    public void doRefresh() {
        if (ListUtil.isEmpty(data.getInterestItemList())) {
            new RequestInterestTask().execute();
        } else {
            interestAdapter.setNewData(data.getInterestItemList());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventInterestSelectedAllCleared(EventInterestSelectedAllCleared event) {
        doRefresh();
    }


    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
        unbinder.unbind();
    }


    public class RequestInterestTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(getActivity())
                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                data.getInterestItemList().add(InterestItem.newBuilder().allSelected(true).build());
                Response<ResponseBody> response = ApiManager.getService()
                        .getSetup(SetupUtil.GROUP_TYPE_CATEGORY, BuildConfig.appVersion, data.getId())
                        .execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                } else {
                    String json = RetrofitUtil.getResponseBodyAsString(response);
                    List<Setup> setupList = JSON.parseArray(json, Setup.class);
                    for (Setup setup : setupList) {
                        data.getInterestItemList().add(InterestItem.newBuilder()
                                .id(setup.getId())
                                .title((String) setup.getData().get("name"))
                                .build());
                    }
                }
                if (AccountUtil.isLogin()) {
                    response = ApiManager.getService()
                            .getUserTag(AccountUtil.getCurrentUser().getId(), data.getId(), SetupUtil.GROUP_TYPE_CATEGORY)
                            .execute();
                    if (response.code() != ResponseCode.OK) {
                        throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                    } else {
                        String json = RetrofitUtil.getResponseBodyAsString(response);
                        List<Tag> tagList = JSON.parseArray(json, Tag.class);
                        for (Tag tag : tagList) {
                            data.getInterestItemList().add(InterestItem.newBuilder()
                                    .id(tag.getId())
                                    .title(tag.getName())
                                    .build());
                        }
                    }
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                data.getInterestItemList().clear();
                ToastX.show(((Exception) o).getMessage());
            } else {
                interestAdapter.setNewData(data.getInterestItemList());
            }
        }
    }
}
